<template>
  <div class="flex items-center justify-center min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
    <!-- 注册卡片容器 -->
    <div class="w-full max-w-md p-8 space-y-8 bg-white rounded-xl shadow-2xl transform transition-all duration-300 hover:shadow-2xl">
      <!-- Logo和标题区域 -->
      <div class="text-center">
        <div class="flex justify-center mb-4">
          <img 
            src="/images/logo.png" 
            alt="PyScreenBrain Logo" 
            class="h-20 w-20 object-contain"
          />
        </div>
        <h2 class="text-2xl font-bold text-gray-900 mb-2">创建新账户</h2>
        <p class="text-sm text-gray-600">加入我们，开始您的AI之旅</p>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="p-3 bg-red-50 border border-red-200 rounded-lg">
        <div class="flex items-center">
          <svg class="w-5 h-5 text-red-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
          </svg>
          <span class="text-sm text-red-700">{{ error }}</span>
        </div>
      </div>

      <!-- 成功提示 -->
      <div v-if="success" class="p-3 bg-green-50 border border-green-200 rounded-lg">
        <div class="flex items-center">
          <svg class="w-5 h-5 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
          </svg>
          <span class="text-sm text-green-700">{{ success }}</span>
        </div>
      </div>

      <!-- 注册表单 -->
      <form @submit.prevent="handleRegister" class="space-y-6">
        <!-- 用户名输入框 -->
        <div>
          <label for="username" class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg class="h-5 w-5 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
              </svg>
            </div>
            <input
              id="username"
              v-model="form.username"
              type="text"
              required
              class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
              placeholder="请输入用户名"
              @input="validateUsername"
            />
            <div v-if="usernameError" class="absolute inset-y-0 right-0 pr-3 flex items-center">
              <svg class="h-5 w-5 text-red-500" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
              </svg>
            </div>
          </div>
          <p v-if="usernameError" class="mt-1 text-sm text-red-600">{{ usernameError }}</p>
        </div>



        <!-- 密码输入框 -->
        <div>
          <label for="password" class="block text-sm font-medium text-gray-700 mb-2">密码</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg class="h-5 w-5 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd" />
              </svg>
            </div>
            <input
              id="password"
              v-model="form.password"
              :type="showPassword ? 'text' : 'password'"
              required
              class="block w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
              placeholder="请输入密码"
              @input="validatePassword"
            />
            <button
              type="button"
              class="absolute inset-y-0 right-0 pr-3 flex items-center"
              @click="showPassword = !showPassword"
            >
              <svg class="h-5 w-5 text-gray-400 hover:text-gray-600" fill="currentColor" viewBox="0 0 20 20">
                <path v-if="showPassword" d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" v-else />
              </svg>
            </button>
          </div>
          <p v-if="passwordError" class="mt-1 text-sm text-red-600">{{ passwordError }}</p>
          <div class="mt-1 text-xs text-gray-500">
            密码要求：至少8个字符，包含大小写字母和数字
          </div>
        </div>

        <!-- 确认密码输入框 -->
        <div>
          <label for="confirmPassword" class="block text-sm font-medium text-gray-700 mb-2">确认密码</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg class="h-5 w-5 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd" />
              </svg>
            </div>
            <input
              id="confirmPassword"
              v-model="form.confirm_password"
              :type="showConfirmPassword ? 'text' : 'password'"
              required
              class="block w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
              placeholder="请再次输入密码"
              @input="validateConfirmPassword"
            />
            <button
              type="button"
              class="absolute inset-y-0 right-0 pr-3 flex items-center"
              @click="showConfirmPassword = !showConfirmPassword"
            >
              <svg class="h-5 w-5 text-gray-400 hover:text-gray-600" fill="currentColor" viewBox="0 0 20 20">
                <path v-if="showConfirmPassword" d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" v-else />
              </svg>
            </button>
          </div>
          <p v-if="confirmPasswordError" class="mt-1 text-sm text-red-600">{{ confirmPasswordError }}</p>
        </div>

        <!-- 注册按钮 -->
        <div>
          <button
            type="submit"
            :disabled="isLoading || hasErrors"
            class="group relative w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 transform hover:scale-[1.02] active:scale-[0.98]"
          >
            <!-- 加载动画 -->
            <svg v-if="isLoading" class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            {{ isLoading ? '注册中...' : '立即注册' }}
          </button>
        </div>

        <!-- 登录引导 -->
        <div class="text-center">
          <p class="text-sm text-gray-600">
            已有账户？
            <a href="/auth/login" class="font-medium text-blue-600 hover:text-blue-500 transition-colors duration-200">立即登录</a>
          </p>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { register } from '@/services/auth'

// 路由和认证服务
const router = useRouter()

/**
 * 注册表单数据
 */
const form = reactive({
  username: '',
  password: '',
  confirm_password: ''
})

/**
 * 响应式数据
 */
const isLoading = ref(false)
const error = ref('')
const success = ref('')
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const usernameError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')

/**
 * 计算属性：检查是否有验证错误
 */
const hasErrors = computed(() => {
  return !!usernameError.value || !!passwordError.value || !!confirmPasswordError.value
})

/**
 * 验证用户名格式
 */
const validateUsername = () => {
  const value = form.username.trim()
  
  if (!value) {
    usernameError.value = '请输入用户名'
    return
  }
  
  if (value.length < 3) {
    usernameError.value = '用户名至少需要3个字符'
    return
  }
  
  if (value.length > 20) {
    usernameError.value = '用户名不能超过20个字符'
    return
  }
  
  const usernameRegex = /^[a-zA-Z0-9_]+$/
  if (!usernameRegex.test(value)) {
    usernameError.value = '用户名只能包含字母、数字和下划线'
    return
  }
  
  usernameError.value = ''
}



/**
 * 验证密码强度
 */
const validatePassword = () => {
  const value = form.password
  
  if (!value) {
    passwordError.value = '请输入密码'
    return
  }
  
  if (value.length < 8) {
    passwordError.value = '密码至少需要8个字符'
    return
  }
  
  const hasUpperCase = /[A-Z]/.test(value)
  const hasLowerCase = /[a-z]/.test(value)
  const hasNumbers = /\d/.test(value)
  
  if (!hasUpperCase || !hasLowerCase || !hasNumbers) {
    passwordError.value = '密码必须包含大小写字母和数字'
    return
  }
  
  passwordError.value = ''
  
  // 如果确认密码已有值，重新验证
    if (form.confirm_password) {
      validateConfirmPassword()
    }
}

/**
   * 验证确认密码
   */
  const validateConfirmPassword = () => {
    const value = form.confirm_password
    
    if (!value) {
      confirmPasswordError.value = '请确认密码'
      return
    }
    
    if (value !== form.password) {
      confirmPasswordError.value = '两次输入的密码不一致'
      return
    }
    
    confirmPasswordError.value = ''
  }

/**
 * 处理注册操作
 */
const handleRegister = async () => {
  // 清除之前的消息
  error.value = ''
  success.value = ''
  
  // 验证所有字段
  validateUsername()
  validatePassword()
  validateConfirmPassword()
  
  // 如果有验证错误，不提交
  if (hasErrors.value) {
    error.value = '请修复表单中的错误'
    return
  }
  
  isLoading.value = true
  
  try {
    await register({
      username: form.username.trim(),
      password: form.password,
      confirm_password: form.confirm_password
    })
    
    success.value = '注册成功！正在跳转到登录页面...'
    
    // 2秒后跳转到登录页面
    setTimeout(() => {
      router.push('/auth/login')
    }, 2000)
    
  } catch (err: any) {
    console.error('注册失败:', err)
    error.value = err.response?.data?.message || '注册失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
/* 可以在这里添加组件特定的样式 */
</style>